package controller;

import beans.HttpConfig;
import net.sf.json.JSONObject;
import org.apache.hadoop.hdfs.BlockReaderFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

import static beans.HttpConfig.scriptFileUri;
import static engine.BIEngine0_1.AlgorithmOperator.chmod;

public class SocketLogDetail extends HttpServlet {
    private static final long serialVersionUID = -8808369437012065082L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String logFilePath = request.getParameter("logFile");
        if(logFilePath!=null)
        {
            String logFold = HttpConfig.socketLogFileUri;
            File foldFile = new File(logFold);
            if(!foldFile.exists())
            {
                foldFile.mkdir();
                chmod(logFold);
            }
            File file = new File(logFold+logFilePath);
            BufferedReader bufferedReader;
            if(logFilePath.substring(logFilePath.lastIndexOf(".")+1,logFilePath.length()).equals("log")){
                bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
            } else{
                bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"GBK"));
            }
            String temp = "";
            StringBuffer result = new StringBuffer();
            while ((temp=bufferedReader.readLine())!=null)
            {
                temp = new String(temp.getBytes(),"utf-8");
                result.append(temp+"\r\n");
            }
            JSONObject resultJson = new JSONObject();
            resultJson.put("preview",result.toString());
            resultJson.put("url",logFilePath);
            response.getWriter().write(resultJson.toString());
        }else{
            response.getWriter().write("error");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
